package gate

import (
	"base"
	"emma/protobuf"
	"github.com/golang/protobuf/proto"
	"leaf/gate"
	"proto/player"
	"test_client/chanrpc"
	"test_client/logic/gate/api"
	. "test_client/logic/internal"
)

type gateSystem struct {
	agent gate.Agent
}

var system = new(gateSystem)

func init() {
	gate_api.Send = system.Send
	gate_api.Write = system.Write
}

func init() {
	Skeleton.AfterInit(func() {
		Skeleton.RegisterChanRPC(chanrpc.NewGateAgent, system.newAgent)
		Skeleton.RegisterChanRPC(chanrpc.CloseGateAgent, system.closeAgent)
	})
}

func (*gateSystem) newAgent(args []interface{}) {
	agent := args[0].(gate.Agent)

	base.Logger.Debug("new center agent, remote address: %s, local address: %s", agent.RemoteAddr(), agent.LocalAddr())
	system.agent = agent
}

func (*gateSystem) closeAgent(args []interface{}) {
	agent := args[0].(gate.Agent)

	base.Logger.Debug("close center agent, remote address: %s, local address: %s", agent.RemoteAddr(), agent.LocalAddr())
	system.agent = nil
}

func (*gateSystem) Send(data proto.Message) {
	if data == nil {
		base.Logger.Error("data is nil")
		return
	}

	msg := new(proto_player.Request)
	msg.Name = protobuf.Name(data)

	var err error
	msg.Data, err = proto.Marshal(data)
	if err != nil {
		base.Logger.Error("marshal data failed, reason: %v", err)
		return
	}

	system.Write(msg)
	//base.Logger.Debug("request %s, %s", msg.Name, data)
}

func (*gateSystem) Write(msg proto.Message) {
	if system.agent == nil {
		return
	}

	if msg == nil {
		base.Logger.Error("data is nil")
		return
	}

	system.agent.WriteMsg(msg)
	base.Logger.Debug("send request %s, %s", protobuf.Name(msg), msg)
}
